package stark.app.function.netusage;

import android.view.View;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.ConvertUtils;
import com.stark.netusage.lib.NetUsageInfoList;
import com.stark.netusage.lib.NetUsageUtil;

import androidx.recyclerview.widget.LinearLayoutManager;
import stark.app.R;
import stark.app.databinding.FragmentNetUsageRecentDemoBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.inf.IRetCallback;
import stark.common.basic.utils.PermissionUtil;
import stark.common.basic.utils.TimeUtil;

/**
 * Author：daizhongbin on 2022/8/10
 * Email：1027154338@qq.com
 * Desc:
 */
public class NetUsageRecentFragment extends BaseNoModelFragment<FragmentNetUsageRecentDemoBinding> {

    private boolean showMobile = true;
    private NetUsageDateAdapter mDateAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_net_usage_recent_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.tvMobile.setOnClickListener(this);
        mDataBinding.tvWifi.setOnClickListener(this);

        mDataBinding.rvUsages.setLayoutManager(new LinearLayoutManager(getContext()));
        NetUsageDateAdapter dateAdapter = new NetUsageDateAdapter();
        mDateAdapter = dateAdapter;
        mDataBinding.rvUsages.setAdapter(dateAdapter);

    }

    @Override
    protected void initData() {
        if (PermissionUtil.hasUsageStatsPermission()) {
            updateData();
        }
    }

    @Override
    protected void onClickCallback(View v) {
        if (v == mDataBinding.tvMobile) {
            showMobile = true;
            updateData();
        } else if (v == mDataBinding.tvWifi) {
            showMobile = false;
            updateData();
        }
    }

    public void updateData() {
        long endTime = TimeUtil.getStartOfToday();
        long startTime = endTime - 7 * TimeConstants.DAY;
        NetUsageUtil.getAllInPeriod(startTime, endTime, new IRetCallback<NetUsageInfoList>() {
            @Override
            public void onResult(NetUsageInfoList result) {
                if (mDataBinding == null) return;
                long average = showMobile ? result.getMobileAverage() : result.getWifiAverage();
                mDataBinding.tvData.setText(ConvertUtils.byte2FitMemorySize(average, 1));

                mDateAdapter.setNewInstance(result.usageInfos);
            }
        });
    }
}
